package server;

import util.ServletUtil;
import util.StaticResourceUtil;
import webresources.Mapper;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 多线程改造封装的RequestProcessor类
 */
public class RequestProcessor extends Thread {

    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try{
            // 封装Request对象和Response对象
            inputStream = socket.getInputStream();
            Request request = new Request(inputStream);
            outputStream = socket.getOutputStream();
            Response response = new Response(outputStream);
            // 查找servlet
            Servlet servlet = ServletUtil.queryServlet(request, socket, mapper);
            if (servlet == null) {
                // 静态资源处理
                response.outputHtml(request.getUrl());
            } else {
                // 动态资源处理
                servlet.service(request, response);
            }
            StaticResourceUtil.close(socket, inputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            StaticResourceUtil.close(socket, inputStream, outputStream);
        }
    }
}
